package org.example.leetcode.addon.lc151;

import java.util.Collections;
import java.util.LinkedList;
import java.util.List;

public class Solution {
    public String reverseWords(String s) {
        List<String> bucket = new LinkedList<>();
        StringBuilder sb = new StringBuilder();
        char[] chars = s.trim().toCharArray();
        for (int i = 0; i < chars.length; i++) {
            if (chars[i] != ' ') {
                sb.append(chars[i]);
                if (i == chars.length - 1) {
                    bucket.add(sb.toString());
                    sb.delete(0, sb.length());
                }
            } else {
                if (sb.length() != 0) {
                    bucket.add(sb.toString());
                    sb.delete(0, sb.length());
                }
            }
        }

        Collections.reverse(bucket);

        return String.join(" ", bucket);
    }

    public static void main(String[] args) {
        Solution solu = new Solution();
        solu.reverseWords("the sky is blue");
        solu.reverseWords("  hello world  ");
        solu.reverseWords("a good   example");
    }
}
